package com.dong.algorithm.novice.introduction;

/**
 * 算法：给定一个参数N,返回1!+2!+3!+...+N！的结果
 *
 * @author by jiweidong on 2021/11/15.
 */
public class Alg01_SumOfFactorial {

    public static void main(String[] args) {

        System.out.println(sumOfFactorial(3));
        System.out.println(sumOfFactorial2(3));
    }

    // 普通算法
    public static long sumOfFactorial(int n) {
        long result = 0;
        if (n <= 0) {
            return result;
        }

        for (int i = 1; i <= n; i++) {
            result += factorial(i);
        }
        return result;
    }

    private static long factorial(int n) {
        long result = 1;
        for (int i = 1; i <= n; i++) {
            result *= i;
        }
        return result;
    }

    // 高级算法
    public static long sumOfFactorial2(int n) {
        long result = 0;
        if (n <= 0) {
            return result;
        }

        long cur = 1;
        for (int i = 1; i <= n; i++) {
            cur *= i;
            result += cur;
        }
        return result;
    }

}
